package com.example.demo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.entity.ChatMessage;
import com.example.demo.entity.DTO.LoadMessageDTO;
import com.example.demo.entity.DTO.unreadDTO;
import com.example.demo.entity.Message;
import com.example.demo.entity.Result;
import com.example.demo.entity.User;
import com.example.demo.entity.VO.MessageVO;
import com.example.demo.mapper.MessageMapper;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.IMessageService;
import com.example.demo.service.IUserService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static com.example.demo.utils.Constants.MESSAGE_READ;
import static com.example.demo.utils.Constants.MESSAGE_UNREAD;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yolo
 * @since 2025-03-28
 */
@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements IMessageService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private MessageMapper messageMapper;
    @Resource
    private IUserService userService;

    public void savePublicMessage(ChatMessage chatMessage) {
        Message message = BeanUtil.copyProperties(chatMessage, Message.class);
        message.setId(RandomUtil.randomInt());
        message.setSenderId(userMapper.getUserByUsername(chatMessage.getSenderUsername()).getUserId());
        message.setIsRead(MESSAGE_READ);
        save(message);
    }

    public Integer savePrivateMessage(ChatMessage chatMessage) {
        Message message = BeanUtil.copyProperties(chatMessage, Message.class);
        int messageId = RandomUtil.randomInt();
        message.setId(messageId);
        message.setSenderId(userMapper.getUserByUsername(chatMessage.getSenderUsername()).getUserId());
        message.setReceiverId(userMapper.getUserByUsername(chatMessage.getReceiveUsername()).getUserId());
        message.setIsRead(MESSAGE_UNREAD);
        save(message);
        return messageId;
    }

    public void markMessageAsRead(Long messageId) {
        Message message = getById(messageId);
        message.setIsRead(MESSAGE_READ);
        saveOrUpdate(message);
    }

    @Override
    public Result<MessageVO> getUnReadMessageListByUsername(String username) {
        User receiveUser = userMapper.getUserByUsername(username);
        List<unreadDTO> userIdListByReceiveIdAndIsReadFalse = messageMapper.getUserIdListByReceiveIdAndIsReadFalse(receiveUser.getUserId());
        List<Message> lastSessionMessage = messageMapper.getLastMessageSessionByReceiveIdAndReadFalse(receiveUser.getUserId());
        for (com.example.demo.entity.DTO.unreadDTO unreadDTO : userIdListByReceiveIdAndIsReadFalse) {
            unreadDTO.setSenderUsername(userMapper.getUsernameByUserId(unreadDTO.getSenderId()));
            unreadDTO.filter();
        }
        MessageVO messageVO = new MessageVO();
        messageVO.setMessageList(lastSessionMessage);
        messageVO.setUnreadList(userIdListByReceiveIdAndIsReadFalse);
        int totalUnRead = 0;
        for (com.example.demo.entity.DTO.unreadDTO unreadDTO : userIdListByReceiveIdAndIsReadFalse) {
            totalUnRead = totalUnRead + unreadDTO.getCount();
        }
        for (Message message : lastSessionMessage) {
            message.setSenderUsername(userMapper.getUsernameByUserId(message.getSenderId()));
            message.setReceiverUsername(userMapper.getUsernameByUserId(message.getReceiverId()));
            message.filter();
            markMessageAsRead(Long.valueOf(message.getId()));
        }
        messageVO.setData(totalUnRead);
        return Result.success("操作成功!", messageVO);
    }

    @Override
    public Result getChatMessageByMutualUsername(LoadMessageDTO loadMessageDTO) {
        User currentUser = userMapper.getUserByUsername(loadMessageDTO.getCurrentUsername());
        User chatUser = userMapper.getUserByUsername(loadMessageDTO.getChatUsername());
        List<Message> sessionMessage = messageMapper.getSessionMessageByReceiveIdAndSenderId(currentUser.getUserId(), chatUser.getUserId(), loadMessageDTO.getOffset());
        for (Message message : sessionMessage) {
            message.setReceiverUsername(userMapper.getUsernameByUserId(message.getReceiverId()));
            message.setSenderUsername(userMapper.getUsernameByUserId(message.getSenderId()));
            message.filter();
            markMessageAsRead(Long.valueOf(message.getId()));
        }
        Result<Object> result = new Result<>();
        result.setData(sessionMessage);
        return result;
    }

    @Override
    public Result getChatList(LoadMessageDTO loadMessageDTO) {
        User currentUser = userMapper.getUserByUsername(loadMessageDTO.getCurrentUsername());
        List<Integer> idsList = messageMapper.getChatList(currentUser.getUserId());
        List<User> charUserList = new ArrayList<>();
        for (Integer i : idsList) {
            User user = userService.getById(i);
            user.setRole(null);
            user.setUserId(null);
            user.filter();
            charUserList.add(user);
        }
        return Result.success("操作成功", charUserList);
    }

    @Override
    public Result getUnreadCountList(LoadMessageDTO loadMessageDTO) {
        User currentUser = userMapper.getUserByUsername(loadMessageDTO.getCurrentUsername());
        List<unreadDTO> unReadCountList = messageMapper.getUnReadCountListByReceiveId(currentUser.getUserId());
        Integer totalUnreadCount = 0;
        for (unreadDTO unreadDTO : unReadCountList) {
            totalUnreadCount = totalUnreadCount + unreadDTO.getCount();
            unreadDTO.setSenderUsername(userService.getById(unreadDTO.getSenderId()).getUsername());
            unreadDTO.setSenderId(null);
        }
        unReadCountList.get(0).setMessage(totalUnreadCount);
        return Result.success("操作成功!", unReadCountList);
    }

    @Override
    public Result getUnreadCount(String currentUsername) {
        User user = userMapper.getUserByUsername(currentUsername);
        Integer totalUnreadCount = messageMapper.getUnreadCountByUserId(user.getUserId());
        return Result.success("操作成功！", totalUnreadCount);
    }
}
